<%@ page pageEncoding="UTF-8"%>
<%@ page import="java.util.Map.Entry,java.util.*,java.util.regex.*,java.net.*,java.io.*,java.text.*,java.lang.reflect.*,java.util.stream.*"%>
<%@ page import="com.tianxiabuyi.*,com.tianxiabuyi.persist.*,com.tianxiabuyi.model.priv.*,com.tianxiabuyi.model.base.*,com.tianxiabuyi.utils.*"%>
<%@ page import="com.tianxiabuyi.model.priv.*,com.tianxiabuyi.model.base.*,com.tianxiabuyi.model.manage.*,com.tianxiabuyi.model.pojo.*"%>
<%@ page import="org.dom4j.*"%>
<%@ page import="com.tianxiabuyi.weixin.common.message.Article"%>
<%@ page import="com.tianxiabuyi.weixin.common.message.Media"%>
<%@ page import="com.tianxiabuyi.weixin.common.message.MpNews"%>
<%@ page import="com.tianxiabuyi.weixin.common.message.MsgType"%>
<%@ page import="com.tianxiabuyi.weixin.common.message.Text"%>
<%@ page import="com.tianxiabuyi.weixin.qy.message.json.*"%>
<%@ page import="com.tianxiabuyi.weixin.qy.message.*"%>
<%@ page import="com.mchange.v2.resourcepool.ResourcePool" %>
<%!
	static final Integer MANAGE_USER_TYPE = 1;	// 管理员
	static final Integer COMMON_USER_TYPE = 2;  // 普通User表人员
	// 根据user查询所拥有的权限列表
	public List<Privilege> getPrivsByUser(Object user) {
	    Integer uid = null;
	    Integer type = MANAGE_USER_TYPE;
	    if (user instanceof User) {
			uid = ((User)user).getId();
			type = COMMON_USER_TYPE;
		}
	    else if (user instanceof ManageUser)
	        uid = ((ManageUser)user).getId();
	    else
	        return new ArrayList<Privilege>();
		// 查询用户对应的权限id
		List<Integer> privList = QBuilder.db("basedb").select("pr.privId").from("UserRole as ur, PrivilegeRole as pr").where(new Where("ur.userId=", uid).and("ur.roleId=pr.roleId").and("ur.type=", type)).query().getResultObj();
		String privIds = "-1,";
		for (int i = 0; i < privList.size(); i++) {
			Integer pid = privList.get(i);
			privIds += pid + ",";
		}
		privIds = Tools.getDesc(privIds, 0, privIds.length()-1);
		return QBuilder.db("basedb").queryHql("from Privilege where id in (" + privIds + ")");
	}

	// 根据user查询所拥有的菜单列表
	public List<Privilege> getMenusByUser(Object user) {
		return menus(getPrivsByUser(user));
	}

    // 根据用户拥有的所有权限构造带层级的菜单
    public static List<Privilege> menus(List<Privilege> list) {
        List<Privilege> rootmenuList = new ArrayList(); // 一级菜单
        for (int i = 0; i < list.size(); i++) {
            Privilege p = list.get(i);
            Integer parentId = p.getParentId();
            if (parentId == 0) {
                rootmenuList.add(p);
            }
        }
        list.removeAll(rootmenuList);

        // 根据一级菜单查找到最后一级
        Map<Integer, Privilege> menuMap = new LinkedHashMap();
        for (int i = 0; i < rootmenuList.size();i ++) {
            Privilege p = rootmenuList.get(i);
            pase(p, list);
            menuMap.put(p.getId(), p);
        }

        // 格式化好的权限类
        List<Privilege> formatList = new ArrayList();
        for (Map.Entry<Integer, Privilege> entry : menuMap.entrySet()) {
            formatList.add(entry.getValue());
        }
        return formatList;
    }

    // 递归子菜单
    public static Privilege pase(Privilege p, List<Privilege> list) {
        for (int i = 0; i< list.size(); i++) {
            Privilege subPrivilege = list.get(i);
            if (subPrivilege.getParentId().toString().equals(p.getId().toString())) {
                List<Privilege> childs = p.getChilds();
                childs.add(subPrivilege);
                pase(subPrivilege, list);
            }
        }
        return p;
    }

	// 判断对象是否为空
	boolean isEmpty(Object o) {
		if (o == null) {
			return true;
		}
		String type = o.getClass().getName();
		if ("java.lang.String".equals(type)) {
			String result = (String)o;
			return result.trim().length() == 0;
		} else if (type.startsWith("java.util.") && type.endsWith("List")) {
			List result = (List)o;
			return result.size() == 0;
		} else if (type.startsWith("java.util.") && type.endsWith("Map")) {
			Map result = (Map)o;
			return result.size() == 0;
		} else if (type.startsWith("[")) {
			return Array.getLength(o) == 0;
		}
		return false;
	}

	// 下划线转驼峰
	public  String camelName(String name) {
	    StringBuilder result = new StringBuilder();
	    // 快速检查
	    if (name == null || name.isEmpty()) {
	        // 没必要转换
	        return "";
	    } else if (!name.contains("_")) {
	        // 不含下划线，仅将首字母小写
	        return name.substring(0, 1).toLowerCase() + name.substring(1);
	    }
	    // 用下划线将原始字符串分割
	    String camels[] = name.split("_");
	    for (String camel :  camels) {
	        // 跳过原始字符串中开头、结尾的下换线或双重下划线
	        if (camel.isEmpty()) {
	            continue;
	        }
	        // 处理真正的驼峰片段
	        if (result.length() == 0) {
	            // 第一个驼峰片段，全部字母都小写
	            result.append(camel.toLowerCase());
	        } else {
	            // 其他的驼峰片段，首字母大写
	            result.append(camel.substring(0, 1).toUpperCase());
	            result.append(camel.substring(1).toLowerCase());
	        }
	    }
	    return result.toString();
	}

	// 反射执行本地方法,方法参数只有input,有其他参数请传入input
	public Message invoke(Object obj, String method, Input input) {
		if (obj == null || method == null || input == null)
			return new Message(-1, "执行错误，请检查参数");
		Class clazz = obj.getClass();
		try {
			Method function = clazz.getDeclaredMethod(method, Input.class);
			return (Message)function.invoke(obj, input);
		}  catch (Exception e) {
			e.printStackTrace();
			return new Message(30041, String.format("执行方法%s失败，%s", new Object[]{method, e.getClass()}));
		}
	}


	// 竖线分割的字符串转list
	List<String> stringToList(String str) {
		List<String> list = new ArrayList<String>();
		if (!isEmpty(str)) {
			String[] strs = str.split("\\|");
			for (int  i = 0; i < strs.length; i++) {
				list.add(strs[i]);
			}
		}
		return list;
	}

	// 检测当前登录用户是否有某项菜单的权限
	public boolean checkAuth(String button, Input input) {
		if (input == null)
			return false;
		HttpSession session = input.getRequest().getSession();
		if (session == null || button == null || session.getAttribute("roles") == null)
			return false;
		List<Privilege> list = (List<Privilege>)session.getAttribute("roles");
		for (Privilege p:list) {
			String name = p.getName();
			if (button.equals(Tools.getDesc(name)))
				return true;
		}
		return false;
		// return list.stream().filter(privilege->button.equals(privilege.getName())).count() > 0;

	}

	// 提示跳转
	public void alertMsg(JspWriter out, String message, String url) {
		try {
			out.println(String.format("<script>alert('%s');location.href='%s'</script>", new Object[]{message, url}));
		} catch (Exception e) {

		}
		return;
	}

	public User getCurrentUser(Input input) {
	   return (User)input.getRequest().getSession().getAttribute("User");
	}

	static final Integer STATUS_ENABLE = 1;
	static final Integer STATUS_DISABLE = 0;
	static final Integer USER_PATIENT = 100;
	static final Integer USER_EMPLOYEE = 200;
	// 默认头像
	static final String USER_AVATAR_M = "http://image.eeesys.com/default/user_m.png";      // 男性用户
	static final String USER_AVATAR_FM = "http://image.eeesys.com/default/user_fm.png";     // 女性用户
	static final String EMPLOYEE_AVATAR_M = "http://image.eeesys.com/default/doctor_m.png";  // 男性医生
	static final String EMPLOYEE_AVATAR_FM = "http://image.eeesys.com/default/doctor_fm.png"; // 女性医生
	static final String DEFAULT_AVATAR = "http://image.eeesys.com/default/default_avatar.png"; // 默认头像
	// 天下布医企业账号
	static final String CORPID = "wx997ea53e3821a059";  
	static final String CORPSECRET = "5ZhlQckJGhoQqV4Dg6wKprozVwOQ8AE5-R41DgLuAu15YarOPU7cOdvv0N4TtDM0"; 
%>
<%
	Input input = new Input(request); // 请求对象
	String act = input.getDesc("act", "-999"); // 访问类型
	String path = input.getPath();
	Message msg = new Message();
%>
